package com.f5tts.common;

import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.util.UriUtils;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class DownloadFile {
    public String downloadFile(HttpServletResponse response, InputStream inputStream, String filename) {
        filename = UriUtils.encode(filename, "UTF-8");
        response.setContentType("multipart/form-data;");
        response.setContentType("application/force-download");
        //设置下载的文件名
        response.addHeader("Content-Disposition", "attachment;fileName*=UTF-8''" + filename);
        byte[] buffer = new byte[1024];
        try (BufferedInputStream bis = new BufferedInputStream(inputStream)) {
            OutputStream os = response.getOutputStream();
            int i = bis.read(buffer);
            while (i != -1) {
                os.write(buffer, 0, i);
                i = bis.read(buffer);
            }
        } catch (Exception e) {
            return e.getMessage();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException ignored) {
                }
            }
        }

        return null;
    }
}
